/**
 * Created by Zhao Bo En on 2017/12/13
 */
//日期转换

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var WDS = null;  //选择日时的数据
var WMS = null;  //选择月时的数据
var startTime = null;       //开始时间，表格导出数据使用
var endTime = null;         //结束时间，表格导出数据使用
var farmName = null;       //电场名称，表格导出数据使用
var fileName = null;
$(function () {
    //$.ajaxSettings.async = false;
    showDiv();
    /*var options=$("#cs option:selected");//获取id为"cs"的选中的项
    alert(options.val());*/
    dateTiemSelect();
    dateTiemSelect2();
    var aa = $('#selectQuxian', window.parent.document).find("option:selected").text();
    console.log(aa);
    $("#query").click(function () {
        // alert("111");
        if ($("#startTime").val() === "") {
            layer.msg("输入开始时间！", {icon: 2});
            $("#endTime").val("");
        }
        var startTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
        var aa = $('#selectQuxian', window.parent.document).find("option:selected").text();
        if (startTime >= endTime) {
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime").val("");
            $("#endTime").val("");
            return false;
        }else {
            $("#windAccuracyStatistics").bootstrapTable("destroy");
            new tableFactory($("#startTime").val(), $("#endTime").val(), aa)
            load();
        }
    })
    $("#query2").click(function () {
        // alert("111");
        if($("#startTime2").val()===""){
            layer.msg("输入开始时间！", {icon: 2});
            $("#endTime2").val("");
        }
        var startTime = new Date($("#startTime2").val().replace(/\-/g, "\/"));
        var endTime = new Date($("#endTime2").val().replace(/\-/g, "\/"));
        var aa = $('#selectQuxian', window.parent.document).find("option:selected").text();
        if(startTime >=endTime){
            layer.msg("开始时间不能大于结束时间！", {icon: 2});
            $("#startTime2").val("");
            $("#endTime2").val("");
            return false;
        }else {
            $("#windAccuracyStatistics").bootstrapTable("destroy");
            new tableFactory($("#startTime2").val(), $("#endTime2").val(), aa)
            load();
        }
    })
    var options=$("#cs option:selected");//获取id为"cs"的选中的项

    //  fileName = aa.substring(31,aa.length);
    // console.log(fileName);
    if(options.val() == 4){
        startTime = $("#startTime").val();
        endTime = $("#endTime").val();
    }
    if(options.val() == 5){
        startTime = $("#startTime2").val();
        endTime = $("#endTime2").val();
    }

    var table = new tableFactory(startTime,endTime,aa);
});

//点击时间查询
function dateTiemSelect(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime', //新增的日期
            type: 'date',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#071f3a',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime', //新增的日期
            type: 'date',
            theme: '#071f3a',//自定义主题
            max: '2028-12-31',//限制最大日期
            ready: function(date){

            },
            done: function(value, date, endDate){//选中之后的对调函数

            }
        });
    });
}

//点击时间查询
function dateTiemSelect2(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#startTime2', //新增的日期
            type: 'month',//日期类型date表示年月日
            /*  trigger: 'click',//如果绑定的元素非输入框，则默认事件为：click*/
            theme: '#071f3a',//自定义主题
            min: '2014-1-1',//限制最小日期
            max: '2028-12-31'//限制最大日期
        });
        laydate.render({
            elem: '#endTime2', //新增的日期
            type: 'month',
            theme: '#071f3a',//自定义主题
            max: '2028-12-31',//限制最大日期
            ready: function(date){

            },
            done: function(value, date, endDate){//选中之后的对调函数

            }
        });
    });
}
//初始化加载数据
function load() {
    var index = layer.load(1);
    var options=$("#cs option:selected");//获取id为"cs"的选中的项
    var intervalnum=$("#cf option:selected");//获取id为"cf"的预报间隔时间
    var factor=$("#met option:selected");//获取id为"cf"的预报间隔时间
    var WfDS;  //查询的所有数据
    var date = new Array(); //所有日期
    var r_speed = new Array();//风速相关性系数
    var rmse_val_speed = new Array();//风速均方根误差值
    var mae_val_speed = new Array();//风速平均绝对误差值

    var farmCityName = $('#selectQuxian', window.parent.document).val();//获取父页面的元素

    if(options.val() == 4){ //得到当前下拉框选中的值
        var p = {
            "startTime":$("#startTime").val(),
            "endTime":$("#endTime").val(),
            "factor":encodeURIComponent(factor.val()),
            "cityName":farmCityName,
            "intervalnum":intervalnum.val()
        };
        //获取实况数据
        $.ajax({    //获取数据(日)
            url : "../meteorologyForecastPrecision/selectMeteorologyDataByDay",
            type : "get",
            contentType : "application/json",
            dataType : "json",
            data : p,
            success : function(data) {
                WDS = data;
                WfDS = data;
                $.each(data, function (index, item) {
                    var time1 = new Date(parseInt(item.stime)).Format("yyyy-MM-dd");
                    date.push(time1); //日期
                    if(item.r_speed != null){
                        r_speed.push((item.r_speed).toFixed(2));
                    }
                    if(item.rmse_val_speed != null){
                        rmse_val_speed.push(item.rmse_val_speed.toFixed(2));
                    }
                    if(item.mae_val_speed != null){
                        mae_val_speed.push(item.mae_val_speed.toFixed(2));
                    }

                });
                lodaTu(factor.val(),date,r_speed,rmse_val_speed,mae_val_speed);
                var totalRmseValSpeed = 0;
                var totalMaeValSpeed = 0;
                var totalRSpeed = 0;
                var totalRmseAverage = 0;
                var totalMaeAverage = 0;
                var totalRSpeedAverage = 0;
                var j = 0;
                for(var i in WfDS){
                    totalRmseValSpeed += WfDS[i].rmse_val_speed;
                    totalMaeValSpeed += WfDS[i].mae_val_speed;
                    totalRSpeed += WfDS[i].r_speed;
                    j++;
                }
                totalRmseAverage = totalRmseValSpeed/j;
                totalMaeAverage = totalMaeValSpeed/j;
                totalRSpeedAverage = totalRSpeed/j;
                var a={stime:'平均值',rmse_val_speed:totalRmseAverage,mae_val_speed:totalMaeAverage,r_speed:totalRSpeedAverage};
                WfDS.push(a);
                $("#windAccuracyStatistics").bootstrapTable("load", WfDS);
                layer.close(index);
            },
        });
    }
    if(options.val() == 5){
        var p = {
            "startTime":$("#startTime2").val(),
            "endTime":$("#endTime2").val(),
            "factor":encodeURIComponent(factor.val()),
            "cityName":farmCityName,
            "intervalnum":intervalnum.val()
        };
        //获取实况数据
        $.ajax({    //获取数据(月)
            url : "../meteorologyForecastPrecision/selectMeteorologyDataByMonth",
            type : "get",
            contentType : "application/json",
            dataType : "json",
            data : p,
            success : function(data) {
                WMS = data;
                WfDS = data;
                $.each(data, function (index, item) {
                    var time1 = new Date(parseInt(item.stime)).Format("yyyy-MM");
                    date.push(time1); //日期
                    if(item.r_speed != null){
                        r_speed.push((item.r_speed).toFixed(2));
                    }
                    if(item.rmse_val_speed != null){
                        rmse_val_speed.push(item.rmse_val_speed.toFixed(2));
                    }
                    if(item.mae_val_speed != null){
                        mae_val_speed.push(item.mae_val_speed.toFixed(2));
                    }
                });
                lodaTu(factor.val(),date,r_speed,rmse_val_speed,mae_val_speed);
                var totalRmseValSpeed = 0;
                var totalMaeValSpeed = 0;
                var totalRSpeed = 0;
                var totalRmseAverage = 0;
                var totalMaeAverage = 0;
                var totalRSpeedAverage = 0;
                var j = 0;
                for(var i in WfDS){
                    totalRmseValSpeed += WfDS[i].rmse_val_speed;
                    totalMaeValSpeed += WfDS[i].mae_val_speed;
                    totalRSpeed += WfDS[i].r_speed;
                    j++;
                }
                totalRmseAverage = totalRmseValSpeed/j;
                totalMaeAverage = totalMaeValSpeed/j;
                totalRSpeedAverage = totalRSpeed/j;
                var a={stime:'平均值',rmse_val_speed:totalRmseAverage,mae_val_speed:totalMaeAverage,r_speed:totalRSpeedAverage};
                WfDS.push(a);
                $("#windAccuracyStatistics").bootstrapTable("load", WfDS);
                layer.close(index);
            },
        });
    }


}

//表格样式
function tableFactory(startTime,endTime,fileNames) {
    var options = $("#cs option:selected");//获取id为"cs"的选中的项
    var factorall = $("#met option:selected").val();//获取id为"cf"的预报间隔时间
    var unit = 'm/s';
    if (factorall === '温度')
        unit = '℃';
    if (factorall === '湿度')
        unit = '%rh';
    if (factorall === '降水')
        unit = 'mm';
    var me = this;
    //me.data = null;//有功功率
    me.windData = null;//电站信息
    var init = function () {
        $.when(me.getWindData()).then(function () {
            $("#windAccuracyStatistics").bootstrapTable({
                method: 'get',				  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "desc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect:true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 5,
                pageList: [5,20,30],
                editable:true,//是否可以行内编辑
                showExport: true,//是否显示导出按钮
                exportDataType:'all',//导出全部
                exportTypes:[  'csv'], //导出文件类型
                export: 'glyphicon-export icon-share',
                exportOptions: {
                    // ignoreColumn: [0,1],  //忽略某一列的索引
                    fileName: startTime + "_" + endTime,  //文件名称设置
                    // worksheetName: 'sheet1',  //表格工作区名称
                    // tableName: '总台帐报表',
                    //  excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
                    // onMsoNumberFormat: DoOnMsoNumberFormat
                },
                columns: [{
                    title: '日期',
                    field: 'stime',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        if(value == '平均值'){
                            return '平均值';
                        }else {
                            var csop = $("#cs option:selected");
                            if (csop.val() == 4) {
                                return new Date(parseInt(value)).Format("yyyy-MM-dd");
                            } else
                                return new Date(parseInt(value)).Format("yyyy-MM");

                        }
                        //return me.getWfDSTime(row.r_speed);
                    }
                },
                    {
                        title: '相关性系数',
                        field: 'r_speed',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            return (value).toFixed(2);
                        }
                    },
                    {
                        title: '均方根误差值(' + unit + ')',
                        field: 'rmse_val_speed',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            return value.toFixed(2);
                        }
                    }, {
                        title: '平均绝对误差值(' + unit + ')',
                        field: 'mae_val_speed',
                        align: 'center',
                        valign: 'middle',
                        formatter: function (value, row, index) {
                            return value.toFixed(2);
                        }
                    },

                ],
                onEditableSave: function (field, row, oldValue, $el) {//编辑之后的事件
                    var p ={
                        id:row.fid,
                        power:row.power
                    }
                    $.ajax({
                        type: "post",
                        url: "../roseManage/edit",
                        data:row,//后台使用了实体类，前台就不能用Json.stringify
                        dataType: 'JSON',
                        success: function (data, status) {
                            /*if (status == "success") {
                                alert('提交数据成功');
                            }*/
                        },
                        error: function () {
                            alert('编辑失败');
                        },
                        complete: function () {

                        }

                    });
                }
            });
            //me.loadData();
            load();
        });
    }
    init();
}

tableFactory.prototype = {

    //加载电站信息
    getWindData:function () {
        var me = this;
        $.getJSON('../windManage/selectAll', '', function (_data) {
            me.WindData = _data;
        })
    },
    getWindById: function (farmid) {
        var farmName = '';
        var me = this;
        $.each(me.WindData, function (index, item) {
            if (item.farmid === farmid) {
                farmName = item.farmname;
                return false;
            }
        });
        return farmName;
    },

    /*获取时间*/
    getWfDSTime:function (r_speed) {
        var time1 = "";
        var speed="";
        var options=$("#cs option:selected");//获取id为"cs"的选中的项
        if(options.val() == 4){
            if(WDS.length>0){
                $.each(WDS, function (index, item) {
                    var r = item.r_speed;
                    if(r == r_speed){
                        time1 = new Date(parseInt(item.dataday)).Format("yyyy-MM-dd");
                        return false;
                    }
                });
                return time1;
            }
        }
        if(options.val() == 5){
            if(WMS.length>0){
                $.each(WMS, function (index, item) {
                    var r = item.r_speed;
                    if(r == r_speed){
                        time1 = new Date(parseInt(item.datamonth)).Format("yyyy-MM");
                        return false;
                    }
                });
                return time1;
            }
        }

    },

}

function lodaTu(factor,date,r_speed,rmse_val_speed,mae_val_speed) {
    var myChart = echarts.init(document.getElementById("main"));
    var fft = factor + '均方根误差值';
    var ave = factor + '平均绝对误差值';
    var unit = 'm/s';
    if (factor === '温度')
        unit = '℃';
    if (factor === '湿度')
        unit = '%rh';
    if (factor === '降水')
        unit = 'mm';
    option = {
        title: {
            text: '准确率统计',
            textStyle: {
                color: '#fff'
            }
        },
        tooltip: {
            show: true,
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type:'cross',
                crossStyle:{
                    color:'#ddd'
                }
            }
        },
        legend: {
            data: [factor+'相关性系数',factor+'均方根误差值',factor+'平均绝对误差值'],
            selected:{
                fft:false,
                ave:false
            },
            align: 'right',
            right: 10,
            textStyle: {
                color: '#fff',
                fontSize: 14
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            splitLine:{show: false},//去除网格线
            type: 'category',
            //data: ['0m/s-3m/s', '3m/s-6m/s', '6m/s-9m/s', '9m/s-12m/s', '12m/s以上'],
            data:date,
            axisLine:{
                lineStyle:{
                    color:'#9B4E4E',
                    width:1,//这里是为了突出显示加上的
                }
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                }
            }
        }],
        yAxis: [{
            splitLine: {show: false},//去除网格线
            type: 'value',
            max: 1,
            min: 0,
            nameTextStyle: {
                color: '#fff'
            },
            axisLabel: {
                formatter: '{value}',
                textStyle: {
                    fontWeight: "bolder",
                    color: '#fff'
                }
            }
        }, {
            splitLine: {show: false},//去除网格线
            type: 'value',
            name: '误差值(' + unit + ')',
            nameTextStyle: {
                color: '#fff'
            },
            axisLabel: {
                formatter: '{value}',
                textStyle: {
                    fontWeight: "bolder",
                    color: '#fff'
                }
            }
        }],
        dataZoom:[
            {   show:true,
                height:30,
                xAxisIndex: [0],
                bottom:0,
                type: 'slider',
                start: 0,
                end: 60,
                handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
                handleSize:'100%',
                handleStyle: {
                    color:'#9B4E4E'
                }
            },
            {
                show:true,
                type: 'inside',
                height:15,
                start: 1,
                end:50
            }
        ],
        series: [{
                name: factor+'相关性系数',
                type: 'bar',
                yAxisIndex: 0,
                //data: [1, 1, 2, 3, 1],
                barMaxWidth:30,
                data:r_speed,
                //data:windFrequencyMonth,
                //barWidth: 15,
                itemStyle: {
                    normal: {
                        color:'#A52A2A',
                        barBorderRadius: 6,
                    }
                },
            },{
                name: factor+'均方根误差值',
                type: 'bar',
                yAxisIndex: 1,
                //data: [3, 7, 2, 3, 1],
                barMaxWidth:30,
                data:rmse_val_speed,
                //data:windFrequencyQuarter,
                //barWidth: 15,
                itemStyle: {
                    normal: {
                        color:'#00CED1',
                        barBorderRadius: 6,
                    }
                },
            },{
                name: factor+'平均绝对误差值',
                type: 'bar',
                yAxisIndex: 1,
                //data: [3, 7, 2, 3, 1],
                barMaxWidth:30,
                data:mae_val_speed,
                //data:windFrequencyQuarter,
                //barWidth: 15,
                itemStyle: {
                    normal: {
                        color:'#7A378B',
                        barBorderRadius: 6,
                    }
                },
            }
        ]
    };
    myChart.setOption(option);
}

function showDiv() {
    $("#box1").show();
    $("#box2").hide();
    $("select").change(function () {
        var selectedValue = $(this).val();

        if (selectedValue == 4) {

            $("#box1").show();

            $("#box2").hide();
        }
        if (selectedValue == 5) {

            $("#box2").show();

            $("#box1").hide();
        }
    });
}